package jxcmanager.jxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jxcmanager.jxc.mapper.UserMapper;
import jxcmanager.jxc.pojo.User;
import jxcmanager.jxc.query.UserQuery;
import jxcmanager.jxc.service.IUserService;
import jxcmanager.jxc.utils.AssertUtil;
import jxcmanager.jxc.utils.PageResultUtil;
import jxcmanager.jxc.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author Yao
 * @since 2021-10-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public User findUserByUserName(String userName) {
        return this.baseMapper.selectOne(new QueryWrapper<User>().eq("is_del",0).eq("user_name",userName));
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserInfo(User user) {
        /**
         * 用户名的判断 ：非空、唯一
         */
        AssertUtil.isTrue(StringUtil.isEmpty(user.getUsername()),"用户名不能为空！");
        User temp = this.findUserByUserName(user.getUsername());
        AssertUtil.isTrue( null != temp && !(temp.getId().equals(user.getId())),"用户名已存在");
        AssertUtil.isTrue(!(this.updateById(user)),"用户信息更新失败");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUserPassword(String userName, String oldPassword, String newPassword, String confirmPassword) {
        /**
         * 用户名非空且存在
         * 原始密码、新密码、确认密码均非空
         * 原始密码必须正确
         * 新密码与确认密码必须一致、并且不能与原始密码相同
         */
        User user = null;
        user = findUserByUserName(userName);
        AssertUtil.isTrue(null == this.findUserByUserName(userName),"用户不存在或未登录");
        AssertUtil.isTrue(StringUtil.isEmpty(oldPassword),"请输入原始密码");
        AssertUtil.isTrue(StringUtil.isEmpty(newPassword),"请输入新密码");
        AssertUtil.isTrue(StringUtil.isEmpty(confirmPassword),"请输入确认密码");
        AssertUtil.isTrue(!(passwordEncoder.matches(oldPassword,user.getPassword())),"原始密码输入错误");
        AssertUtil.isTrue(!(newPassword.equals(confirmPassword)),"两次密码输入不一致");
        AssertUtil.isTrue(newPassword.equals(oldPassword),"新密码与原始密码不能一致");
        user.setPassword(passwordEncoder.encode(newPassword));
        AssertUtil.isTrue(!(this.updateById(user)),"用户密码更新失败");

    }

    /**
     * 用户信息查询
     * @param userQuery
     * @return
     */
    @Override
    public Map<String, Object> userList(UserQuery userQuery) {
        IPage<User> page = new Page<User>(userQuery.getPage(),userQuery.getLimit());
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("is_del",0);   //查询未删除的用户名
        if (StringUtils.isNotBlank(userQuery.getUserName())){
            queryWrapper.like("user_name",userQuery.getUserName());
        }//如果用户名不为空， 根据用户名进行模糊匹配查询
        page = this.baseMapper.selectPage(page,queryWrapper);
        //根据官网查询的layui框架的数据显示模型填充匹配数据
        return PageResultUtil.getResult(page.getTotal(),page.getRecords());
    }



    /**
     * 添加用户
     * @param user
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveUser(User user) {
        /**
         * 用户名    非空  不能重复
         * 用户密码  默认设置为1-6
         * 用户默认是有效的
         */
        AssertUtil.isTrue(StringUtils.isBlank(user.getUsername()),"用户名不能为空！");
        AssertUtil.isTrue(null != this.findUserByUserName(user.getUsername()),"用户名已存在！");
        user.setPassword(passwordEncoder.encode("123456"));
        user.setIsDel(0);
        AssertUtil.isTrue(!(this.save(user)),"用户记录添加失败！");

    }





    /**
     * 更新用户
     * @param user
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateUser(User user) {
        /**
         * 用户名   非空不可重复
         */
        AssertUtil.isTrue(StringUtils.isBlank(user.getUsername()),"用户名不能为空！");
        User temp = this.findUserByUserName(user.getUsername());
        AssertUtil.isTrue(null!=temp && !(temp.getId().equals(user.getId())),"用户名已存在！");
        AssertUtil.isTrue(!(this.updateById(user)),"用户记录更新失败!");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteUser(Integer[] ids) {
        AssertUtil.isTrue(null == ids || ids.length == 0,"请选择待删除的用户记录id!");
        List<User> list = new ArrayList<User>();
        for (Integer id : ids){
            User temp = this.getById(id);
            temp.setIsDel(1);
            list.add(temp);
        }
        AssertUtil.isTrue(!(this.updateBatchById(list)),"用户记录删除失败！");
    }


}
